<?php
require_once('psalmfunctions.php');
require_once('lyfunctions.php');
$allowPageBreakMidVerse = false;
$slightVerticalSpace = $allowPageBreakMidVerse? '[0.0514in]' : '*[0.0514in]';
$regBold = '/\|+(\\S(?:.*?(?:([a-z])|\\S))?)\|+/i';
$regItalic = '/_+(\\S(?:.*?(?:([a-z])|\\S))?)_+/i';
function escapeTeX($text) {
  return preg_replace('/(?<!\\\\)&/', '\&', $text);
}
function applyTexBoldItalics($text) {
  global $regBold,$regItalic;
  return preg_replace('/(\\\\\\?{\\S})(\\\\text(?:bf|it){)/','$2$1',
            preg_replace('/\\\\\\?{[a-z]?}([^a-z])/i','$1',
                preg_replace($regBold, '\\textbf{$1}\?{$2}',
                    preg_replace($regItalic, '\\textit{$1}\?{$2}', $text))));
}
function applyEmph($text) {
  global $regBold,$regItalic;
  if((strlen($text) - 2) == strlen(str_replace('_','',$text)) &&
    $text[0] == '_' && $text[strlen($text)-1]=='_') {
    return str_replace('_','',$text);
  }
  return preg_replace('/(\\\\\\?{\\S})(\\\\emph{)/','$2$1',
            preg_replace('/\\\\\\?{[a-z]?}([^a-z])/i','$1',
                preg_replace($regItalic, '\\emph{$1}\?{$2}', $text)));
}

$search = array('\'',' ');
$replace= array('\\\'','\ ');
$edition = $_REQUEST['edition'];
$save = $_REQUEST['save'];
$supertitle = mb_strtolower($_REQUEST['supertitle'],'UTF-8');
$fname = mb_strtolower($_REQUEST['filename'],'UTF-8');
$title = mb_strtolower($_REQUEST['title'],'UTF-8');
$subtitle = $_REQUEST['subtitle'];
$includeverses = $_REQUEST['includeverses'];
if($includeverses === '') {
  $includeverses = false;
} else {
  $includeverses = true;
  $_POST['includeverses'] = '1';
}
$genres = $_REQUEST['genre'];
$genrenumbers = $_REQUEST['genrenumber'];
$genrequalifiers = $_REQUEST['genrequalifier'];
$engravings=$_REQUEST['engraving'];
$siglias = $_REQUEST['siglia'];
$addtoengravings=$_REQUEST['addtoengraving'];
$forcepagebreaks = $_REQUEST['forcepagebreak'];
$addspaceaboves = $_REQUEST['addspaceabove'];
$addspacebelows = $_REQUEST['addspacebelow'];
$removespaceaboves = $_REQUEST['removespaceabove'];
$removetranslations = $_REQUEST['removetranslation'];
$raggedlasts = $_REQUEST['raggedlast'];
$psalmtitles = $_REQUEST['psalmtitle'];
$psalmverses = $_REQUEST['psalmverse'];
$numberverseses = $_REQUEST['numberverses'];
$markpenultimateaccents = $_REQUEST['markpenultimateaccent'];
$glorybes = $_REQUEST['glorybe'];
$psalmtones = $_REQUEST['psalmtone'];
$harmonizedpsalmtones = $_REQUEST['harmonizedpsalmtone'];
$sectionIDs = $_REQUEST['sectionID'];
$sectionTypes=$_REQUEST['sectiontype'];
$footer = $_REQUEST['footer'];
$footerText = $_REQUEST['footertext'];
$spaceBelowChants = $_REQUEST['spacebelowchant'];
$spaceAboveChants = $_REQUEST['spaceabovechant'];
$spaceBetweenSystemss = $_REQUEST['spacebetweensystems'];
$spacings=$_REQUEST['spacing'];
$rubrictitlesizes=$_REQUEST['rubrictitlesize'];
$rubrictitlealignments=$_REQUEST['rubrictitlealignment'];
$subsetfonts=$_REQUEST['subsetfonts'];
$publish=$_REQUEST['publish'];

$rubrics = array();

$useModernFontSizes = array_key_exists('engraving-Modern',array_flip($sectionTypes));
$useModernFontSizes = false;
if($useModernFontSizes) {
  $fsizeTitle = 16;
  $fsizeGenre = 13.5;
  $fsizePsalm = 13.5;
} else {
  $fsizeTitle = 18;
  $fsizeGenre = 12;
  $fsizePsalm = 12;
}

$supertitle = applyTexBoldItalics($supertitle);
$title = applyTexBoldItalics($title);


if($footer && !preg_match('/^\s*$/',$footer)) {
  if(!preg_match('/\.txt$/',$footer)) {
    $footer .= '.txt';
  }
  $footerPath = 'library/footers/'.$footer;
  if($footerText && !preg_match('/^\s*$/',$footerText)) {
    $dir = dirname($footerPath);
    if(!file_exists($dir)) {
      mkdir($dir, 0777, true);
    }
    file_put_contents($footerPath, $footerText);
  } else {
    $footerText = file_get_contents($footerPath);
  }
} else {
  $footer = $footerText = '';
}
$footerText = applyTexBoldItalics($footerText);
if(preg_match('/^\s*$/',$footerText)){
  $footerText = '';
} else {
  //$footerText = "\\begin{minipage}{\\textwidth}\\fontsize{8}{8}\\selectfont{{$footerText}}\\end{minipage}
  $footerText = "{\\garamondCaption\\fontsize{8}{8}\\selectfont{{$footerText}}}
";
}

if(preg_match('/^\s*$/',$subtitle)) {
  if(preg_match('/^\s*$/',$title)) {
    $subtitle = '';
  } else {
    $subtitle = '{

\\vspace{12pt}

}';
  }
} else {
  $subtitle = "{
\\vspace{0.05in}\\fontsize{12}{12}\\selectfont\\centering\\textit{{$subtitle}}

\\vspace{12pt}

}
";
}

$dirEdition = preg_replace('/[^a-zA-Z0-9\/\\\\]+/','-',mb_strtolower($edition,'UTF-8'));
$dirEdition = str_replace('\\','/',$dirEdition);
if(preg_match('/^\s*$/',$dirEdition)) {
  $dirEdition = $edition = 'misc';
}

$odir = 'library/scores/' . $dirEdition;

if(preg_match('/^\s*$/',$supertitle)) {
  $supertitle = '';
} else {
  $supertitle = "{\\fontsize{14}{14}\\selectfont\\centering\\textsc{{$supertitle}}

}\\vspace{0.0189in}";
}

$format=$_REQUEST['fmt'];
$width=$_REQUEST['width'];
$pwidth=$_REQUEST['pwidth'];
$vwidth=$_REQUEST['vwidth'];
if($vwidth == '') {
  $vwidth = $width;
}
$verseWidthDifference = ($width - $vwidth) / 2;
$height=$_REQUEST['height'];

if($format == 'pdf-temp') {
  //$format = 'pdf';
  header("Content-type: text/plain");
  print_r($_REQUEST);
  //return;
}


$croppdf=false;
if($_REQUEST['croppdf']=='true'){
  $croppdf=true;
}
if($width==''){
  $width='5';
}
if($pwidth==''){
  $pwidth = 1+$width;
}
if($height==''){
  $height='11';
}
$margin = ($pwidth - $width)/2;
ini_set('magic_quotes_runtime', 0);
if($format==''){
  $format='png';
  $fmtmime='image/png';
} else {
  $fmtmime='application/pdf';
}
function replace_diacritics($matches){
  $s = '\\';
  if($matches[2]) {
    $s='`';
  } else if($matches[3]) {
    $s='\'';
  } else if($matches[4]) {
    $s='^';
  } else if($matches[5]) {
    $s='~';
  } else if($matches[6]) {
    $s='"';
  }
  return "\\$s{$matches[1]}";
}
{
  if(!$fname) {
    $fname = $title;
  }
  $fname = normalizer_normalize($fname,Normalizer::FORM_KD);
  $title = normalizer_normalize($title,Normalizer::FORM_KD);
  $fname = preg_replace('/\p{Mn}/u', '', $fname);
  
  $outFileName = preg_replace('/\'|\W+$/','',$fname);
  $outFileName = preg_replace('/\W+/','-',$outFileName);
  if($_POST['filename']) {
    $_POST['filename'] = $outFileName;
  }
  if($outFileName == '') $outFileName = 'Untitled';
  $tmpFileName = 'tmp/' . str_replace(array('\'',' '),array('','-'),$outFileName);
  $nametex = "$tmpFileName.main.tex";
  $namelytex = "$tmpFileName.main.lytex";
  $namedvi = "$tmpFileName.main.dvi";
  $namepdf = "$tmpFileName.main.pdf";
  $namelog="$tmpFileName.main.log";
  $nameaux="$tmpFileName.main.aux";
  
  if(preg_match('/^\s*$/',$title)) {
    $title = '';
  } else {
    $title = '\\sotitle{' . str_replace("\\\\",'}\\\\*[-3.5pt]\sotitle{',preg_replace_callback('/(\p{L})(?:(\x{0300})|(\x{0301})|(\x{0302})|(\x{0303})|(\x{0308}))/u','replace_diacritics',$title)) . "\n}";
    $title = "{\\fontsize{{$fsizeTitle}}{{$fsizeTitle}}%\\fontseries{sb}
\\selectfont\\centering{\\garamondSubheading\\textsc{{$title}}}

}

";
  }
  $nametexS = str_replace($search,$replace,$nametex);
  $namelytexS = str_replace($search,$replace,$namelytex);
  $namedviS = str_replace($search,$replace,$namedvi);
  $namepdfS = str_replace($search,$replace,$namepdf);
  $namelogS = str_replace($search,$replace,$namelog);
  $nameauxS = str_replace($search,$replace,$nameaux);
  
  $papercmd=<<<EOF
\\usepackage[papersize={{$pwidth}in,{$height}in},top=0.6in,bottom=0.6in,inner={$margin}in,outer={$margin}in,nofoot,head=13.6pt,headsep=15pt,marginparsep=0in,marginpar={$margin}in]{geometry}
\\special{ pdf: pagesize width {$pwidth}truein height {$height}truein}
EOF;

  
  $_POST['href'] = 'http://illuminarepublications.com/editor/psalm.html';
  if($_POST['sectionID'] && $_POST['sectionID'][0]) {
    $json = array();
    foreach($_POST as $key => $val) {
      if($key != 'gabc' && !array_key_exists($key,$sectionKeysNoID)) {
        $json[$key] = $val;
      }
    }
  } else {
    $json = $_POST;
  }
    
  // Write out a template main.tex file that includes the psalms
  $fhandle = fopen($nametex, 'w');
  fwrite($fhandle, <<<EOF
\\documentclass[10pt]{article}
$papercmd
%\\usepackage{fullpage}
\\usepackage{changepage}
\\usepackage{color}
\\usepackage{gregoriotex}
\\usepackage{verse}
\\usepackage[utf8]{luainputenc}
\\usepackage{graphicx}
\\usepackage{ifoddpage}
\\usepackage{fancyhdr}
\\usepackage{fontspec}
\setlength{\headheight}{13.6pt}
\\pagestyle{fancy}
\\reversemarginpar
\\def\\SOUL@error#1{\\relax}
\\def\\PackageError#1#2#3{}
\\usepackage{soul}
\\expandafter\\def\\expandafter\\nocorrlist\\expandafter{\\nocorrlist\\?}
\\newcommand{\\?}[2]{%
  \\sbox0{\\hbox{#1}\\hbox{#2}}%
  \\sbox2{#1#2}%
  \\kern\\dimexpr\\wd2-\\wd0\\relax#2}
\\textwidth {$width}in
\\def\\headrulewidth{0pt}
\\begin{document}
\\setmainfont[Numbers={Proportional,OldStyle},Extension=.otf,UprightFont=*,BoldFont=*-Smbd,ItalicFont=*-It,BoldItalicFont=*-SmbdIt]{GaramondPremrPro}
\\newfontfamily\\garamondCaption[Numbers={Proportional,OldStyle},Extension=.otf,UprightFont=*-Capt,BoldFont=*-SmbdCapt,ItalicFont=*-ItCapt,BoldItalicFont=*-SmbdItCapt]{GaramondPremrPro}
\\newfontfamily\\garamondSubheading[Numbers={Proportional,OldStyle},Extension=.otf,UprightFont=*-Subh,BoldFont=*-SmbdSubh,ItalicFont=*-ItSubh,BoldItalicFont=*-SmbdItSubh]{GaramondPremrPro}
\\newfontfamily\\garamondDisplay[Numbers={Proportional,OldStyle},Extension=.otf,UprightFont=*-Disp,BoldFont=*-SmbdDisp,ItalicFont=*-ItDisp,BoldItalicFont=*-SmbdItDisp]{GaramondPremrPro}
%\\setmainfont[Numbers={Proportional,OldStyle},Extension=.otf,SizeFeatures={
%    {Size={-8.9},UprightFont=*-Capt,BoldFont=*-SmbdCapt,ItalicFont=*-ItCapt,BoldItalicFont=*-SmbdItCapt},
%    {Size={8.9-14.9},UprightFont=*,BoldFont=*-Smbd,ItalicFont=*-It,BoldItalicFont=*-SmbdIt},
%    {Size={14.9-22.9},UprightFont=*-Subh,BoldFont=*-SmbdSubh,ItalicFont=*-ItSubh,BoldItalicFont=*-SmbdItSubh},
%    {Size={22.9-},UprightFont=*-Disp,BoldFont=*-SmbdDisp,ItalicFont=*-ItDisp,BoldItalicFont=*-SmbdItDisp}
%  }]{GaramondPremrPro}
%\\setmainfont[Numbers={Proportional,OldStyle},BoldFont=GaramondPremrPro-Smbd.otf]{GaramondPremierPro}
\\newfontfamily\\versiculum{Versiculum}
%\\newfontfamily\\garamondLining[Numbers={Proportional,Lining},Extension=.otf,BoldFont=*-Smbd,ItalicFont=*-It,BoldItalicFont=*-SmbdIt]{GaramondPremrPro}
\\font\\garamondLining=GaramondPremrPro-Bd-lf-ly1 at 8pt
\\font\\garamondHymnNumbers=GaramondPremrPro-lf-ly1 at 16pt
\\font\\garamondMeterNumbers=GaramondPremrPro-lf-ly1 at 7pt
\\font\\garamondVerseNumber=GaramondPremrPro-osf-ly1 at 12pt
\\font\\garamondGenre=GaramondPremrPro-lf-ly1 at {$fsizeGenre}pt
\\font\\garamondItalicLord=GaramondPremrPro-It-lf-sc-ly1 at 12pt
\\cfoot[]{}%
\\lhead[]{}%
\\chead[\\garamondMeterNumbers{\\MakeUppercase\\rightmark}]{\\garamondMeterNumbers{\\MakeUppercase\\rightmark}}%
\\setlength{\\parindent}{0in}
\\gresetstafflinefactor{13}
\\def\\greinitialformat#1{%
{\\fontsize{38}{38}\\selectfont #1}}
\\gdef\\grelowchoralsignstyle#1{{\\garamondCaption\\fontsize{8}{8}\\selectfont #1}}
\\gdef\\grehighchoralsignstyle#1{{\\garamondCaption\\fontsize{8}{8}\\selectfont #1}}
\\def\\greabovelinestextstyle#1{\\hspace*{-5pt}\\small\\textit{#1}}

\\sodef\\sotitle{}{0.043em}{0.24em}{2em plus.1em minus.1em}
\\sodef\\SOTITLE{}{0.23em}{0.46em}{2em plus.1em minus.1em}
\\newlength{\\saveleftmargini}

\\setlength{\\saveleftmargini}{\\leftmargini}
\\setlength{\\leftmargini}{0.1806in}
\\setlength{\\vgap}{12bp}
%\\setlength{\\vleftskip}{4bp}
\\settowidth{\\vleftskip}{\\Vbar}
\\addtolength{\\vleftskip}{-2\\vleftskip}
\\addtolength{\\vleftskip}{\\leftmargini}

\\setlength{\\stanzaskip}{0.1975in}
%\\settowidth{\\leftmargini}{\\Vbar}
%\\addtolength{\\leftmargini}{\\vleftskip }

%\\setlength{\\footskip}{0.475in}

\\def\\dualcomment#1#2{%
  {\\fontsize{10}{10}\\selectfont
  \\setlength{\\parindent}{0pt}%
  \\vbox{#1 \\hfill #2}%
  \\nopagebreak\\vspace{0.25em}%
  \\relax}%
}
\\def\\grestar{%
  *%
  \\relax%
}
\\def\\Abar{%
  {\\versiculum a}%
  \\relax%
}

\\def\\Rbar{%
  {\\versiculum r}%
  \\relax%
}

\\def\\Vbar{%
  {\\versiculum v}%
  \\relax%
}
\\def\\gretranslationformat#1{%
  \\fontsize{10}{10}\\selectfont\\textit{#1}%
  \\relax %
}
\\def\\pdfliteral#1{%
  \\relax%
}
\\def\\UseAlternatePunctumCavum{%
\\gdef\\grepunctumcavumchar{\\gregoriofont\\char 75}%
\\gdef\\grelineapunctumcavumchar{\\gregoriofont\\char 76}%
\\gdef\\grepunctumcavumholechar{\\gregoriofont\\char 78}%
\\gdef\\grelineapunctumcavumholechar{\\gregoriofont\\char 80}%
\\relax %
}
$supertitle%
$title%
$subtitle%
\\renewcommand{\\poemtitlefont}{\\centering}
\\setlength{\\beforepoemtitleskip}{-0.125in}
\\setlength{\\afterpoemtitleskip}{-0.0875in}

EOF
);
  foreach($sectionTypes as $index => $sectionType) {
    $sectionID = $sectionIDs[$index];
    $genre = $genres[$index];
    $engraving = $engravings[$index];
    $genrenumber = $genrenumbers[$index];
    $forcepagebreak = $forcepagebreaks[$index];
    $addspaceabove = $addspaceaboves[$index];
    $addspacebelow = $addspacebelows[$index];
    $removespaceabove = $removespaceaboves[$index];
    $removetranslation = $removetranslations[$index];
    if($genrenumber=='0'){
      $genrenumber='';
    }
    $genrequalifier = $genrequalifiers[$index];
    
    $acGenreQualifier = preg_split('/\\r|\\n/',file_get_contents('library/autocompletes/genreQualifiers.txt'),NULL,PREG_SPLIT_NO_EMPTY);
    if($genrequalifier != '' && !in_array($genrequalifier,$acGenreQualifier)) {
      $acGenreQualifier[] = $genrequalifier;
      file_put_contents('library/autocompletes/genreQualifiers.txt',implode("\n",$acGenreQualifier));
    }

    if($sectionType == 'hairline') {
      if($forcepagebreak) {
        $topspace = '\newpage';
      } else if($addspaceabove) {
        $topspace = '\vspace{14pt}';
      } else {
        $topspace = '';
      }
      if($addspacebelow) {
        $botspace = '\vspace{14pt}';
      } else {
        $botspace = '';
      }
      fwrite($fhandle, "
$topspace
\\hrule
$botspace
");
    } else if($sectionType == 'rubric') {
      $rubrictitlesize = $rubrictitlesizes[$index];
      $rubrictitlealignment = $rubrictitlealignments[$index];
      $rubric = array('title'=>$genre, 'rubric'=>$engraving, 'titlesize'=>$rubrictitlesize, 'titlealignment'=>$rubrictitlealignment);
      $rubrics[] = $rubric;
      if($rubrictitlesize == '') {
        $rubrictitlesize = '15';
      }
      if($rubrictitlealignment == '') {
        $rubrictitlealignment = 'center';
      }
      if($genre && strlen($genre) > 0 && $rubrictitlealignment == 'center') {
        $rubricAlignment = '\\centering';
        $genre = "$rubricAlignment $genre
\\nopagebreak
\\\\";
      } else {
        $rubricAlignment = '';
      }
      if($forcepagebreak) {
        $topspace = '\newpage';
      } else if($addspaceabove) {
        $topspace = '\vspace{35pt}';
      } else if($removespaceabove) {
        $topspace = '\vspace{7pt}';
      } else {
        $topspace = '\vspace{21pt}';
      }
      if($addspacebelow) {
        $botspace = '\vspace{14pt}';
      } else {
        $botspace = '';
      }
      if($genre && strlen($genre) > 0) {
        $genre = <<<EOF
{\\noindent\\fontsize{{$rubrictitlesize}}{{$rubrictitlesize}}\\selectfont $genre

}
EOF
;
        $vspace = '\\vspace{15pt}';
      } else {
        $genre = '';
        $vspace = '';
      }
      if($engraving && strlen($engraving) > 0) {
        $engraving = preg_replace('/(\r?\n)+/',"\\\\\\\\\n",$engraving);
        $engraving = <<<EOF
$vspace
\\setlength{\\parindent}{0in}
{\\fontsize{10}{10}\\selectfont\\textit{{$engraving}}}
EOF
;
      } else {
        $engraving = '';
      }
      $genre = escapeTeX($genre);
      fwrite($fhandle, <<<EOF
$topspace

$genre
$engraving
$botspace
EOF
);
      //if($index != count($genres)-1){
      //  fwrite($fhandle, '\\\\');
      //}
      //fwrite($fhandle, "\n");
    } else if($sectionType == 'text') {
      $acGenre = preg_split('/\\r|\\n/',file_get_contents('library/autocompletes/title.txt'),NULL,PREG_SPLIT_NO_EMPTY);
      if($genre != '' && !in_array($genre,$acGenre)) {
        $acGenre[] = $genre;
        file_put_contents('library/autocompletes/title.txt',implode("\n",$acGenre));
      }
      $newpage = '';
      if($forcepagebreak) {
        $newpage = '\newpage';
      }
      if($addspaceabove) {
        $topspace = '\vspace{28pt}';
      } else if($removespaceabove) {
        $topspace = '';
      } else {
        $topspace = '\vspace{14pt}';
      }
      if($addspacebelow) {
        $botspace = '\vspace{20pt}';
      } else {
        $botspace = '\vspace{6pt}';
      }
      if(substr($engraving,-4) != '.txt'){
        $engraving .= '.txt';
      }
      $engravingPath = 'library/texts/'.$engraving;
      $referenceText = file_get_contents($engravingPath);
      $isFormatted = (FALSE !== strpos($referenceText,'_') OR FALSE !== strpos($referenceText,'|') OR FALSE !== strpos($referenceText,"\n"));
      
      $section = array(
        'genre' => $genre,
        'genrenumber' => $genrenumber,
        'genrequalifier' => $genrequalifier,
        'engraving' => $engraving,
        'sectionID' => $sectionID,
        'sectionType' => $sectionType,
        'forcepagebreak' => $forcepagebreak,
        'addspaceabove' => $addspaceabove,
        'removespaceabove' => $removespaceabove
      );
      
      if($genrenumber) {
        $genrenumber = "\\marginpar[\\hfill\\garamondLining{{$genrenumber}~~~~~~}]{\\garamondLining{~~~~~~{$genrenumber}}}";
      }
      if($genrequalifier) {
        $genrequalifier = applyEmph($genrequalifier);
        $genre = $genre . " \\textit{($genrequalifier)}";
      }
      if($genre != '') {
        $genre = applyTexBoldItalics($genre);
        $genre = "
{\\noindent\\garamondGenre $genre\\vspace{-1.2pt}$genrenumber\\vspace{1.2pt}
\\\\*


}";
      } else {
        $genre = '';
      }
      $sectionID = saveSection($section);
      $json['sectionID'][$index] = $sectionID;
      if($isFormatted) {
        $referenceText = applyTexBoldItalics($referenceText);
        $referenceText = str_replace("\n","\\\\\n",$referenceText);
      } else {
        $referenceText = "\\textit{{$referenceText}}";
      }
      $genre = escapeTeX($genre);
      $referenceText = escapeTeX($referenceText);
      fwrite($fhandle, <<<EOF
$newpage %
\\begin{minipage}{\\textwidth}
$topspace %
$genre
\\setlength{\\parindent}{0.1806in}
{\\fontsize{12}{12}\\selectfont{{$referenceText}}}
\\end{minipage}
$botspace
EOF
);
      if($index != count($genres)-1 && $sectionTypes[$index+1]=='text'){
        fwrite($fhandle, '\\\\');
      }
      fwrite($fhandle, "\n");
    } else if($sectionType == 'hymn') {
      if($forcepagebreak) {
        $topspace = '\newpage';
      } else if($addspaceabove) {
        $topspace = '\vspace{28pt}';
      } else if($removespaceabove) {
        $topspace = '';
      } else {
        $topspace = '\vspace{14pt}';
      }
      $spaceBetweenSystems = $spaceBetweenSystemss[$index];
      if(preg_match('/^\s*$/',$spaceBetweenSystems)) {
        $spaceBetweenSystems = '6pt plus 1fil minus 5pt';
      };
      $engravingInfo = loadLy($engraving,true);
      $engravingInfo['width'] = $width;
      $engravingInfo['raggedlast'] = ($raggedlast && $raggedlast != 0)? 't' : '';
      $engraving = getLy($engravingInfo,false,true);
      $title = $engravingInfo['name'];
      $tune = $engravingInfo['tune-data']['name'];
      $tuneAuthor = $engravingInfo['tune-data']['author'];
      $tuneHarmonization = $engravingInfo['tune-data']['harmonization'];
      $textAuthor = $engravingInfo['text-data']['author'];
      $textTranslator = $engravingInfo['text-data']['translator'];
      $meter = $engravingInfo['tune-data']['meter'];
      if(!$meter) {
        $meter = $engravingInfo['text-data']['meter'];
      }
      $theme = $theme = $engravingInfo['theme'];
      if(!$theme) {
        $theme = $engravingInfo['text-data']['theme'];
      }
      if($theme) {
        $settheme = '\markright{' + escapeTeX($theme) + '}';
      } else {
        $settheme = '';
      }
      $belowHymnLeftOne = '';
      $belowHymnRightOne = '';
      $belowHymnLeftTwo = '';
      $belowHymnRightTwo = '';
      $belowHymnLeftThree = '';
      $belowHymnRightThree = '';
      $belowHymnLeftFour = '';
      $belowHymnRightFour = '';
      $belowHymnOne = '';
      $belowHymnTwo = '';
      $belowHymnThree = '';
      $belowHymnFour = '';
      if($tune) {
        $belowHymnRightOne = escapeTeX($tune);
      }
      if($meter) {
        $temp = '\garamondMeterNumbers{' + escapeTeX($meter) + '}';
        if($belowHymnRightOne) {
          $belowHymnRightTwo = $temp;
        } else {
          $belowHymnRightOne = $temp;
        }
      }
      if($tuneAuthor) {
        $belowHymnLeftOne = escapeTeX("MELODY: $tuneAuthor");
      }
      if($tuneHarmonization) {
        $temp = escapeTeX("HARMONIZATION: $tuneHarmonization");
        if($belowHymnLeftOne) {
          $belowHymnLeftTwo = $temp;
        } else {
          $belowHymnLeftOne = $temp;
        }
      }
      if($textAuthor) {
        $temp = escapeTeX("TEXT: $textAuthor");
        if($belowHymnLeftOne) {
          if($belowHymnLeftTwo) {
            $belowHymnLeftThree = $temp;
          } else {
            $belowHymnLeftTwo = $temp;
          }
        } else {
          $belowHymnLeftOne = $temp;
        }
      }
      if($textTranslator) {
        $temp = escapeTeX("TRANSLATOR: $textTranslator");
        if($belowHymnLeftOne) {
          if($belowHymnLeftTwo) {
            if($belowHymnLeftThree) {
              $belowHymnLeftFour = $temp;
            } else {
              $belowHymnLeftThree = $temp;
            }
          } else {
            $belowHymnLeftTwo = $temp;
          }
        } else {
          $belowHymnLeftOne = $temp;
        }
      }
      if($belowHymnLeftOne || $belowHymnRightOne) {
        $belowHymnOne = "\\makebox[0pt][l]{{$belowHymnLeftOne}}%
\\makebox[\\textwidth][c]{}%
\\makebox[0pt][r]{{$belowHymnRightOne}}";
      }
      if($belowHymnLeftTwo || $belowHymnRightTwo) {
        $belowHymnOne .= '\\\\*[-3.5pt]';
        $belowHymnTwo = "\\makebox[0pt][l]{{$belowHymnLeftTwo}}%
\\makebox[\\textwidth][c]{}%
\\makebox[0pt][r]{{$belowHymnRightTwo}}";
      }
      if($belowHymnLeftThree || $belowHymnRightThree) {
        $belowHymnTwo .= '\\\\*[-3.5pt]';
        $belowHymnThree = "\\makebox[0pt][l]{{$belowHymnLeftThree}}%
\\makebox[\\textwidth][c]{}%
\\makebox[0pt][r]{{$belowHymnRightThree}}";
      }
      if($belowHymnLeftFour || $belowHymnRightFour) {
        $belowHymnThree .= '\\\\*[-3.5pt]';
        $belowHymnFour = "\\makebox[0pt][l]{{$belowHymnLeftFour}}%
\\makebox[\\textwidth][c]{}%
\\makebox[0pt][r]{{$belowHymnRightFour}}";
      }
      $ofilename = $engravingInfo['filename'];
      if(!$ofilename) {
        $ofilename = $engravingInfo['name'];
      }
      $ofilename = normalizeFilename($ofilename);
      //$italicline = $engravingInfo['commentary'];
      //$usernotesline = $engravingInfo['user-notes'];
      //$annotation = $engravingInfo['annotation'];
      $tmpfname = str_replace('\'','',"tmp/$ofilename-$index");
      $namepdfT = "$tmpfname.pdf";
      $namely = "$tmpfname.ly";
      $nameps = "$tmpfname.ps";
      $nameSystems = "$tmpfname-systems";
      
      $namepdfTS = str_replace('\'','\\\'',$namepdfT);
      $namelyS = str_replace('\'','\\\'',$namely);
      $namepsS = str_replace('\'','\\\'',$nameps);
      
      $twidth = 72 * $width;
      $theight = 72 * $height;
      // write out ly file
      file_put_contents($namely, $engraving);
      // run lilypond
      exec("export HOME=/home/sacredmusic && /home/sacredmusic/bin/ly214 -dbackend=eps -dno-gs-load-fonts -dinclude-eps-fonts -dno-point-and-click --ps -o\"{$tmpfname}\" \"$namely\" 2>&1", $lyOutput, $lyRetVal);
      if($lyRetVal){
        @header("Content-type: text/plain");
        echo implode("\n",$lyOutput);
        return;
      }
      $sysCount = file_get_contents("$nameSystems.count");
      $includeGraphics = "";
      while($sysCount > 0) {
        $namepdfT = "$tmpfname-$sysCount.pdf";
        $nameps = "$tmpfname-$sysCount.eps";
        exec("export HOME=/home/sacredmusic && gs -q -dSAFER -dEPSCrop -dCompatibilityLevel=1.4 -dNOPAUSE -dBATCH -r1200 -sDEVICE=pdfwrite -sOutputFile=\"{$namepdfT}\" -c.setpdfwrite -f\"{$nameps}\" 2>&1", $gsOutput, $gsRetVal);
        unlink($nameps);
        $includeGraphics = "\\includegraphics{{{$tmpfname}-{$sysCount}}.pdf}%\n" . $includeGraphics;
        --$sysCount;
        if($sysCount > 0) {
          $includeGraphics = "\\vspace{{$spaceBetweenSystems}}\\\\\n" . $includeGraphics;
        }
      }
      $includeEngraving = $includeGraphics;
      fwrite($fhandle, <<<EOF
$topspace %
\\checkoddpage%
\\ifoddpage%
\\makebox[0pt][l]{}%
\\makebox[\\textwidth][c]{\\garamondSubheading\\fontsize{16}{16}\\selectfont $title}%
\\makebox[0pt][r]{\\garamondHymnNumbers{{$genrenumber}}}%
\\else%
\\makebox[0pt][l]{\\garamondHymnNumbers{{$genrenumber}}}%
\\makebox[\\textwidth][c]{\\garamondSubheading\\fontsize{16}{16}\\selectfont $title}%
\\makebox[0pt][r]{}%
\\fi%
$settheme\\\\*[8pt]
$includeEngraving\\\\*[4pt]
{\\garamondCaption\\fontsize{7}{7}\\selectfont%
$belowHymnOne%
$belowHymnTwo%
$belowHymnThree%
$belowHymnFour%
}%
\\noindent
EOF
);
    } else { // !rubric, !text, !hymn
      $isModern = preg_match('/Modern$/',$sectionType);
      $acGenre = @preg_split('/\\r|\\n/',file_get_contents('library/autocompletes/genre.txt'),NULL,PREG_SPLIT_NO_EMPTY);
      if($genre != '' && !in_array($genre,$acGenre)) {
        $acGenre[] = $genre;
        file_put_contents('library/autocompletes/genre.txt',implode("\n",$acGenre));
      }

      $siglia = $siglias[$index];
      $addtoengraving = $addtoengravings[$index];
      $psalmtitle = $psalmtitles[$index];
      $psalmverse = $psalmverses[$index];
      $numberverses = $numberverseses[$index];
      $markpenultimateaccent = $markpenultimateaccents[$index];
      $glorybe = $glorybes[$index];
      $spacing = $spacings[$index];
      $psalmtone = $psalmtones[$index];
      $harmonizedpsalmtone = $harmonizedpsalmtones[$index];
      $spaceBelowChant = $spaceBelowChants[$index];
      $spaceAboveChant = $spaceAboveChants[$index];
      $raggedlast = $raggedlasts[$index];
      if($spaceBelowChant == '') {
        $spaceBelowChant = '0';
      }
      if($spaceAboveChant == '') {
        $spaceAboveChant = '0';
      }
      if($harmonizedpsalmtone == '') {
        $harmonizedpsalmtone = '0';
      }
      
      $section = array(
        'genre' => $genre,
        'genrenumber' => $genrenumber,
        'genrequalifier' => $genrequalifier,
        'engraving' => $engraving,
        'siglia' => $siglia,
        'addtoengraving' => $addtoengraving,
        'psalmtone' => $psalmtone,
        'harmonizedpsalmtone' => $harmonizedpsalmtone,
        'spacebelowchant' => $spaceBelowChant,
        'spaceabovechant' => $spaceAboveChant,
        'sectionID' => $sectionID,
        'sectionType' => $sectionType,
        'forcepagebreak' => $forcepagebreak,
        'addspaceabove' => $addspaceabove,
        'removespaceabove' => $removespaceabove,
        'raggedlast' => $raggedlast,
        'psalmtitle' => $psalmtitle,
        'psalmverse' => $psalmverse,
        'numberverses' => $numberverses,
        'markpenultimateaccent' => $markpenultimateaccent,
        'glorybe' => $glorybe,
        'spacing' => $spacing,
        'removetranslation' => $removetranslation
      );
      $sectionID = saveSection($section);
      $json['sectionID'][$index] = $sectionID;
      $siglia = mb_strtolower($siglia,'UTF-8');
      
      // Process psalm verse...
      if($harmonizedpsalmtone == '1' && $psalmtone) {
        if($isModern) {
          $modPsalmTone = $psalmtone;
        } else {
          $modPsalmTone = str_replace('.gabc','.json',$psalmtone);
        }
        $hptEngravingInfo = loadLy($modPsalmTone);
        if($hptEngravingInfo === FALSE) {
          $harmonizedpsalmtone = '';
        } else {
          $hptEngravingInfo['layout'] = 'satb';
          $hptEngravingInfo['width'] = $width;
          $hptEngravingInfo['raggedlast'] = 't';
          $harmonizedpsalmtone = getLy($hptEngravingInfo,false,true);
        }
      } else {
        $harmonizedpsalmtone = '';
      }
      if($isModern) {
        $spaceBelowChant = '0.125';
        $engravingInfo = loadLy($engraving);
        if($includeverses) {
          $psalmtone = loadLy($psalmtone);
          if(!$harmonizedpsalmtone) {
            $engravingInfo['sop'] .= ' ' . $addtoengraving . ' \\relative c\' { ' . $psalmtone['sop'] . ' } ';
            $engravingInfo['ten'] .= ' ' . $addtoengraving . ' \\relative c\' { ' . $psalmtone['ten'] . ' } ';
            $engravingInfo['alt'] .= ' ' . $addtoengraving . ' \\relative c\' { ' . $psalmtone['alt'] . ' } ';
            $engravingInfo['bas'] .= ' ' . $addtoengraving . ' \\relative c\' { ' . $psalmtone['bas'] . ' } ';
          }
          $psalmToneInfo = lyPsalmToneInfo($psalmtone);
        }
        $engravingInfo['width'] = $width;
        $engravingInfo['raggedlast'] = ($raggedlast && $raggedlast != 0)? 't' : '';
        $engraving = getLy($engravingInfo,false,true);
      } else {
        $engraving = engravingGABC($engraving);
        if($removetranslation) {
          $engraving = preg_replace('/((?:$|\))[^(]*)\[[^]]+\]/','$1',$engraving);
        }
        if($includeverses) {
          $psalmtone = psalmGABC($psalmtone);
          $gabc = $engraving . $addtoengraving;
          if(!$harmonizedpsalmtone) {
            $gabc = $gabc . "\n" . $psalmtone;
          }
          $psalmToneInfo = psalmToneInfo($psalmtone);
        } else {
          $gabc = $engraving;
        }
      }
      
      if($includeverses) {
        if(!$psalmverse || preg_match('/^\s*$/',$psalmverse)) {
          $psalmverse = psalmRef($psalmtitle, $psalmToneInfo, $glorybe, 'Psalm', 'rgp', $markpenultimateaccent);
        } else {
          $psalmverse = preg_replace('/\s+$/D', '', $psalmverse);
          if($glorybe) {
            $psalmverse .= "\n\n" . gloryBe($psalmToneInfo);
          }
          if(!$markpenultimateaccent) {
            $psalmverse = removeEscapedDiacritics($psalmverse);
          }
        }
      }
      
      if($genrequalifier) {
        $genrequalifier = applyEmph($genrequalifier);
        $genre = $genre . " \\textit{($genrequalifier)}";
      }
      $hasGenre = ($genre != '');
      $genre = applyTexBoldItalics($genre);
      if($genrenumber != '') {
        $genrenumber = "\\marginpar[\\hfill\\garamondLining{{$genrenumber}~~~~~~}]{\\garamondLining{~~~~~~{$genrenumber}}}";
      }
      if($hasGenre || ($genrenumber && strlen($genrenumber)>0)) {
        $genre = "
{\\noindent\\garamondGenre $genre\\nopagebreak\\vspace{-1.2pt}\\nopagebreak$genrenumber\\nopagebreak\\vspace{1.2pt}\\nopagebreak
\\nopagebreak
}\\nopagebreak
";
      } else {
        $genre = '';
      }
      $psalmtitle = applyTexBoldItalics($psalmtitle);
      if(preg_match('/^\s*$/',$psalmtitle)) {
        $psalmtitle = '';
      } else {
        $psalmtitle = "\\vspace{-0.138in}
{\\poemtitlefont{{$psalmtitle}
}\\\\*[0.138in]
}";
      }
      $flagverse = '\\flagverse{\\Vbar}';
      if($numberverses) {
        $versenumber = 1;
        $flagverse = "\\flagverse{\\garamondVerseNumber{{$versenumber}.}}";
      }
      if($includeverses && $psalmverse && !preg_match('/^\s*$/',$psalmverse)) {
        $lines = explode("\n", $psalmverse);
        $val = "\\begin{patverse}
%\\setlength{\\baselineskip}{0in}
$psalmtitle
$flagverse";
        $indentpattern = array();
        $v = false;
        $forceIndent = false;
        for($i=0; $i < count($lines); ++$i) {
          $line = $lines[$i];
          $nextLine = $lines[1 + $i];
          if(preg_match('/^[ \t\r]*$/',$line)) {
            if($v) {
              if($numberverses) {
                $versenumber++;
                $flagverse = "\\flagverse{\\garamondVerseNumber{{$versenumber}.}}";
              }
              $val .= "\n\n$flagverse";
              $v = false;
            }
          } else {
            $forceIndentNextTime = false;
            $val .= "\n" . $line . '\\\\';
            $add = (!$nextLine || preg_match('/^\s*$/',$nextLine))? '!' : 
                  (($nextLine && preg_match('/^\S/',$nextLine))? $slightVerticalSpace : '*');
            if(preg_match('/†\s*$/',$line)) {
              $forceIndentNextTime = true;
              $val .= '*';
            } else {
              $val .= $add;
              if($format == 'pdf-temp') {
                echo "   : $line\n";
                echo "$i($add): $nextLine\n";
              }
            }
            $v = true;
            $indentpattern[] = ($forceIndent || preg_match('/^\\s/',$line))? 1 : 0;
            $forceIndent = $forceIndentNextTime;
          }
        }
        $val .= '\\end{patverse}';
        $val = '\\indentpattern{' . implode($indentpattern) . '}' . $val;
        $val = applyTexBoldItalics($val);
        $val = preg_replace('/\blord\b/i','\\textsc{lord}',$val);
        $val = preg_replace('/(\\\\textit{[^\\\\}]*)\\\\textsc{([^}]*)}/i','$1{\\garamondItalicLord $2}',$val);
        $psalmverse = "\\begin{verse}
\\begin{adjustwidth}{{$verseWidthDifference}in}{{$verseWidthDifference}in}
$val
\\end{adjustwidth}
\\end{verse}
";
      } else {
        $psalmverse = '\vspace{8pt}';
      }
      
      if($harmonizedpsalmtone) {
        $ofilename = $hptEngravingInfo['filename'];
        //$italicline = $hptEngravingInfo['commentary'];
        //$usernotesline = $hptEngravingInfo['user-notes'];
        //$annotation = $hptEngravingInfo['annotation'];
        $tmpfname = str_replace('\'','',"tmp/$ofilename-$index");
        $namepdfT = "$tmpfname.pdf";
        $namely = "$tmpfname.ly";
        $nameps = "$tmpfname.ps";
        $nameSystems = "$tmpfname-systems";
        
        $namepdfTS = str_replace('\'','\\\'',$namepdfT);
        $namelyS = str_replace('\'','\\\'',$namely);
        $namepsS = str_replace('\'','\\\'',$nameps);
        
        $twidth = 72 * $width;
        $theight = 72 * $height;
        // write out ly file
        file_put_contents($namely, $harmonizedpsalmtone);
        // run lilypond
        //exec("export HOME=/home/sacredmusic && /home/sacredmusic/bin/ly214 -dno-point-and-click --ps -o\"$tmpfname\" \"$namely\" 2>&1", $lyOutput, $lyRetVal);
        exec("export HOME=/home/sacredmusic && /home/sacredmusic/bin/ly214 -dbackend=eps -dno-gs-load-fonts -dinclude-eps-fonts -dno-point-and-click --ps -o\"{$tmpfname}\" \"$namely\" 2>&1", $lyOutput, $lyRetVal);
        if($lyRetVal){
          @header("Content-type: text/plain");
          echo implode("\n",$lyOutput);
          return;
        }
        $sysCount = file_get_contents("$nameSystems.count");
        $includeGraphics = "";
        while($sysCount > 0) {
          $namepdfT = "$tmpfname-$sysCount.pdf";
          $nameps = "$tmpfname-$sysCount.eps";
          exec("export HOME=/home/sacredmusic && gs -q -dSAFER -dEPSCrop -dCompatibilityLevel=1.4 -dNOPAUSE -dBATCH -r1200 -sDEVICE=pdfwrite -sOutputFile=\"{$namepdfT}\" -c.setpdfwrite -f\"{$nameps}\" 2>&1", $gsOutput, $gsRetVal);
          unlink($nameps);
          $includeGraphics = "\\includegraphics{{{$tmpfname}-{$sysCount}}.pdf}\n" . $includeGraphics;
          --$sysCount;
          if($sysCount > 0) {
            $includeGraphics = "\\linebreak\\vspace{1in plus4mm minus5mm}\n" . $includeGraphics;
          }
        }
        // Run gs on it.
        //exec("export HOME=/home/sacredmusic && gs -q -dSAFER -dDEVICEWIDTHPOINTS=$twidth -dDEVICEHEIGHTPOINTS=$theight -dCompatibilityLevel=1.4 -dNOPAUSE -dBATCH -r1200 -sDEVICE=pdfwrite -dEmbedAllFonts=true -sOutputFile=\"{$namepdfT}\" -c.setpdfwrite -f\"{$nameps}\" 2>&1", $gsOutput, $gsRetVal);
        //if($gsRetVal){
        //  @header("Content-type: text/plain");
        //  echo implode("\n",$lyOutput);
        //  echo "\n\n";
        //  echo implode("\n",$gsOutput);
        //  return;
        //}
        // crop PDF
        //exec("pdfcrop $namepdfTS $namepdfTS 2>&1", $croppdfOutput, $croppdfRetVal);
        //if($croppdfRetVal){
        //  header("Content-type: text/plain");
        //  echo implode("\n",$croppdfOutput);
        //  return;
        //}
        //$includeHarmonizedPsalmTone = "\\begin{center}\\includegraphics{{{$tmpfname}}.pdf}\\end{center}";
        //$includeHarmonizedPsalmTone = "\\begin{center}\\input{{$nameSystems}.tex}\\end{center}";
        $includeHarmonizedPsalmTone = "\\begin{center}$includeGraphics\\end{center}";
      } else {
        $includeHarmonizedPsalmTone = '';
      }
      
      if($isModern) {
        $ofilename = $engravingInfo['filename'];
        $italicline = $engravingInfo['commentary'];
        $usernotesline = $engravingInfo['user-notes'];
        $annotation = $engravingInfo['annotation'];
        $tmpfname = str_replace('\'','',"tmp/$ofilename-$index");
        $namepdfT = "$tmpfname.pdf";
        $namely = "$tmpfname.ly";
        $nameps = "$tmpfname.ps";
        $nameSystems = "$tmpfname-systems";
        
        $namepdfTS = str_replace('\'','\\\'',$namepdfT);
        $namelyS = str_replace('\'','\\\'',$namely);
        $namepsS = str_replace('\'','\\\'',$nameps);
        
        $twidth = 72 * $width;
        $theight = 72 * $height;
        // write out ly file
        file_put_contents($namely, $engraving);
        // run lilypond
        exec("export HOME=/home/sacredmusic && /home/sacredmusic/bin/ly214 -dbackend=eps -dno-gs-load-fonts -dinclude-eps-fonts -dno-point-and-click --ps -o\"{$tmpfname}\" \"$namely\" 2>&1", $lyOutput, $lyRetVal);
        if($lyRetVal){
          @header("Content-type: text/plain");
          echo implode("\n",$lyOutput);
          return;
        }
        $sysCount = file_get_contents("$nameSystems.count");
        $includeGraphics = "";
        while($sysCount > 0) {
          $namepdfT = "$tmpfname-$sysCount.pdf";
          $nameps = "$tmpfname-$sysCount.eps";
          exec("export HOME=/home/sacredmusic && gs -q -dSAFER -dEPSCrop -dCompatibilityLevel=1.4 -dNOPAUSE -dBATCH -r1200 -sDEVICE=pdfwrite -sOutputFile=\"{$namepdfT}\" -c.setpdfwrite -f\"{$nameps}\" 2>&1", $gsOutput, $gsRetVal);
          unlink($nameps);
          $includeGraphics = "\\includegraphics{{{$tmpfname}-{$sysCount}}.pdf}\n" . $includeGraphics;
          --$sysCount;
          if($sysCount > 0) {
            $includeGraphics = "\\vspace{0pt plus3pt minus12pt}\\linebreak\n" . $includeGraphics;
          }
        }
        // Run gs on it.
        //exec("export HOME=/home/sacredmusic && gs -q -dSAFER -dDEVICEWIDTHPOINTS=$twidth -dDEVICEHEIGHTPOINTS=$theight -dCompatibilityLevel=1.4 -dNOPAUSE -dBATCH -r1200 -sDEVICE=pdfwrite -dEmbedAllFonts=true -sOutputFile=\"{$namepdfT}\" -c.setpdfwrite -f\"{$nameps}\" 2>&1", $gsOutput, $gsRetVal);
        //if($gsRetVal){
        //  @header("Content-type: text/plain");
        //  echo implode("\n",$lyOutput);
        //  echo "\n\n";
        //  echo implode("\n",$gsOutput);
        //  return;
        //}
        // crop PDF
        //exec("pdfcrop $namepdfTS $namepdfTS 2>&1", $croppdfOutput, $croppdfRetVal);
        //if($croppdfRetVal){
        //  header("Content-type: text/plain");
        //  echo implode("\n",$croppdfOutput);
        //  return;
        //}
        //$includeEngraving = "\\includegraphics{{{$tmpfname}}.pdf}";
        //$includeEngraving = "\\input{{$nameSystems}.tex}";
        $includeEngraving = $includeGraphics;
      } else { //!$isModern
        $header = gabcHeader($engraving);
        $ofilename = $header['name'];
        if($ofilename=='') {
          $ofilename='Untitled';
        }
      
        $tmpfname = "tmp/$ofilename-$index";
        $namegabc = "$tmpfname.gabc";
        $namegtex = "$tmpfname.tex";
        
        $tmpfnameS = str_replace($search,$replace,$tmpfname);
        $namegabcS = str_replace($search,$replace,$namegabc);
        $namegtexS = str_replace($search,$replace,$namegtex);
        
        $spacingcmd = '';
        if($spacing!='vichi' && $spacing!='smith') {
          $spacing = 'default';
        }
        if(!$includeverses) {
          $spacing = 'vichi';
        }
        //$spacingcmd = "\GreLoadSpaceConf{{$spacing}}";
        $spacingcmd = "\\greremovetranslationspace\\greremovespaceabove\\input gsp-$spacing.tex\\greadaptconfvalues\\gresetverticalspaces\\global\\divide\\greadditionallineswidth by \\grefactor%";
        $italicline = $header['commentary'];
        $usernotesline = $header['user-notes'];
        $annotation = $header['annotation'];
  
// write out gabc
        $handle = fopen($namegabc, 'w');
        if(!$handle){
          header("Content-type: text/plain");
          echo "Unable to create file $namegabc";
          return;
        }
        fwrite($handle, "\xEF\xBB\xBF$gabc");
        fclose($handle);
        
// run gregorio
        exec("/home/sacredmusic/bin/gregorio $namegabcS 2>&1", $gregOutput, $gregRetVal);
        $gregTexContent = file_get_contents($namegtex);
        $gregTexContent = preg_replace('/(\n[^\n]*)\\\\greblockcustos([^\n]*\n)/',"\n\\greblockcustos".'$1$2',$gregTexContent);
        ////$gregTexContent = preg_replace('/(\n[^\n]*\\\\grelastofline[^\n]*\n)/',"\n",$gregTexContent);
        $gregTexContent = preg_replace('/(\\\\greblockcustos[^.]*?\\\\gresyllable{[^}]*}{[^}]*}{[^}]*}{)0(})/','${1}1$2',$gregTexContent);
        file_put_contents($namegtex, $gregTexContent);
        $includeEngraving = "\\UseAlternatePunctumCavum{\\includescore{\"$namegtex\"}}";
      }
      
      $commentcmd = '\dualcomment{}{}';
      $spaceBeforeAnnotation = '\vspace{-6pt}';
      if($siglia) {
        if($italicline && !preg_match('/^\s*$/',$italicline)) {
          $italicline .= ' · ';
        }
        $siglia = str_replace(', asterisk',' *',$siglia);
        $italicline .= '\\textsc{' . $siglia . '}';
      }
      if($usernotesline != '' || $italicline != ''){
        $commentcmd = "\\dualcomment{\\textit{{$usernotesline}}}{\\textit{{$italicline}}}";
        if(!$usernotesline || preg_match('/^\s*$/',$usernotesline)) {
          if(!$italicline || preg_match('/^\s*$/',$italicline)) {
            $spaceBeforeAnnotation = '\vspace{-4pt}';
          }
        } else {
          $spaceBeforeAnnotation = '\vspace{6pt}';
        }
      } else {
        $spaceBeforeAnnotation = '';
      }
      $annotcmd = '';
      $annotsuffix='';
      if($annotation != '') {
        if(preg_match('/[a-g]\d?\*?\s*$/',$annotation, $match)){
          $annotsuffix=$match[0];
          $annotation = substr($annotation,0,strlen($annotation) - strlen($annotsuffix));
        }
        $annotation = preg_replace_callback(
          '/\b[A-Z\d]+\b/',
          create_function(
            '$matches',
            'return strtolower($matches[0]);'
          ),
          $annotation
        );
        $annothelper = "\\fontsize{12}{12}\\selectfont{\\textsc{{$annotation}}$annotsuffix}";
        $annotcmd = "\\gresetfirstlineaboveinitial{{$annothelper}}{{$annothelper}}";
      }
      if($annotcmd != ''){
        $annotwidthcmd = <<<EOF
\\newlength{\\annotwidth}
\\settowidth{\\annotwidth}{{$annothelper}}
\\newlength{\\spacewidth}
%\\setlength{\\spacewidth}{0.6em plus 0em minus 0em}
\\setlength{\\spacewidth}{0.4\\annotwidth}
\\newlength{\\initwidth}
\\settowidth{\\initwidth}{\LARGE I}
\\addtolength{\\spacewidth}{-0.3\\initwidth}
\\setspaceafterinitial{\\spacewidth}
\\setspacebeforeinitial{\\spacewidth}
EOF;
      }
      $annotwidthcmd=<<<EOF
\\setspaceafterinitial{2.2mm plus 0em minus 0em}
\\setspacebeforeinitial{2.2mm plus 0em minus 0em}
EOF;
      if($forcepagebreak) {
        $topspace = '\newpage';
      } else if($addspaceabove) {
        $topspace = '\vspace{28pt}';
      } else if($removespaceabove) {
        $topspace = '';
      } else {
        $topspace = '\vspace{14pt}';
      }
      if($addspacebelow) {
        $botspace = '\vspace{14pt}';
      } else {
        $botspace = '';
      }
      //SECTIONS...
      $genre = escapeTeX($genre);
      $psalmverse = escapeTeX($psalmverse);
      fwrite($fhandle, <<<EOF
$topspace %
$genre$spaceBeforeAnnotation\\vspace{{$spaceAboveChant}in}\\nopagebreak%
$annotcmd \\nopagebreak%\\

$commentcmd
\\nopagebreak\\setgrefactor{17}
{\\fontsize{10}{10}\\selectfont
$annotwidthcmd
\\gretranslationheight = 0.1904in
\\grespaceabovelines=0.1044in
$spacingcmd
%\\fontsize{{$fsizePsalm}}{{$fsizePsalm}}\\selectfont
\\large
\\nopagebreak$includeEngraving
$includeHarmonizedPsalmTone%
\\vspace{{$spaceBelowChant}in}%
$psalmverse
}
$botspace
EOF
    );
  }
}
if(!file_exists($odir)) {
  mkdir($odir, 0777, true);
}
$handle = fopen("$odir/$outFileName.json", 'w');
if(!$handle){
  header("Content-type: text/plain");
  echo "Unable to create file $odir/$outFileName.json";
  return;
}
if($rubrics) {
  $json['rubrics'] = $rubrics;
}
fwrite($handle,json_encode($json));
fclose($handle);
$footerText = escapeTeX($footerText);
fwrite($fhandle, <<<EOF
\\vfill$footerText\\end{document}
EOF
);
  fclose($fhandle);
// Run lualatex.
exec("export HOME=/home/sacredmusic && export TEXMFCNF=.: && /home/sacredmusic/texlive/2013/bin/i386-linux/lualatex -output-directory=tmp -interaction=nonstopmode $nametexS 2>&1", $lualatexOutput, $lualatexRetVal);
// Run lamed on it.
//  exec("export TEXMFCONFIG=/home/sacredmusic/texmf && export TEXMFHOME=/home/sacredmusic/texmf && export HOME=/home/sacredmusic && export TEXMFCNF=.: && lamed -output-directory=tmp -interaction=nonstopmode $nametexS 2>&1", $lamedOutput, $lamedRetVal);
// Run dvipdfm on the .dvi
//  exec("export TEXMFCONFIG=/home/sacredmusic/texmf && export TEXMFHOME=/home/sacredmusic/texmf && export HOME=/home/sacredmusic && dvipdfm -o $namepdfS $namedviS 2>&1", $dvipdfmOutput, $dvipdfmRetVal);
  //if($lamedRetVal){
  if($lualatexRetVal){
    header("Content-type: text/plain");
    echo implode("\n",$lualatexOutput);
    return;
  }
  $deletepdf = ($dirEdition=='' or $outFileName=='Untitled');
  $finalpdf = ($deletepdf?'tmp/tmp.':"$odir/")."$outFileName.pdf";
  $finalpdfS = str_replace($search,$replace,$finalpdf);
  

// Copy the pdf into another directory, or upload to an FTP site.
  if($croppdf) {
    exec("pdfcrop $namepdf $finalpdf 2>&1", $croppdfOutput, $croppdfRetVal);
    if($croppdfRetVal){
      header("Content-type: text/plain");
      echo implode("\n",$croppdfOutput);
      return;
    }
  }
  rename($namepdf,$finalpdf);
  if($publish) {
    if($deletepdf) {
      header("Content-type: text/plain");
      echo "You can only publish a score if it has a title/filename";
      return;
    }
    if(!file_exists("/home/sacredmusic/downloads/$dirEdition")) {
      mkdir("/home/sacredmusic/downloads/$dirEdition", 0775, true);
    }
    copy($finalpdf,"/home/sacredmusic/downloads/$dirEdition/$outFileName.pdf");
    //header('HTTP/1.1 301 Moved Permanently');
    //header("Location: /downloads/$dirEdition/$outFileName.pdf");
    header("Content-type: text/plain");
    echo "Location: /downloads/$dirEdition/$outFileName.pdf";
    return;
  }
  //Instead of just renaming it, let's subset the fonts:
  //exec("gs -q -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pdfwrite -dCompatibilityLevel=1.3 -dEmbedAllFonts=true -dSubsetFonts=true -sOutputFile=$finalpdfS $namepdf");
  //Warning
  header("Content-type: $fmtmime");
  if(!$save) {
    if($format=='pdf'){
      if($subsetfonts) {
        passthru("gs -q -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pdfwrite -dCompatibilityLevel=1.3 -dEmbedAllFonts=true -dSubsetFonts=true -sOutputFile=- $finalpdfS");
      } else {
        $handle = fopen($finalpdf, 'r');
        fpassthru($handle);
        fclose($handle);
      }
    } else {
      passthru("convert -density 480 $finalpdfS +append -resize 25% -limit memory 128 -limit map 256 $format:-");
    }
  }
//  @unlink($namepdf);
//  @unlink($namedvi);
  //@unlink($nametex);
//  @unlink($nameaux);
//  @unlink($namelog);
  if($ofilename != 'gabc') {
//    @unlink($namegtex);
  }
  @unlink($namegabc);
}
?>